package example.hayukleung.speex;

public class Encoder implements Runnable
{
	private volatile int leftSize = 0;
	private final Object mutex = new Object();
	private Speex speex = new Speex();
	private byte[] processedData = new byte[1024];
	private short[] rawData = new short[1024];
	private volatile boolean isRecording;
	private int frameSize;
	private long ts;

	public Encoder()
	{
		super();
		speex.init();
		frameSize = speex.getFrameSize();

	}

	public void run()
	{

		android.os.Process
		    .setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);

		int getSize = 0;
		while (this.isRecording())
		{

			synchronized (mutex)
			{
				while (isIdle())
				{
					try
					{
						mutex.wait();
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
				}
			}
			synchronized (mutex)
			{
				getSize = speex.encode(rawData, 0, processedData, leftSize);
				// 只打印编码结果，没有后续处理
				setIdle();
			}
		}
	}

	public void putData(long ts, short[] data, int size)
	{
		synchronized (mutex)
		{
			this.ts = ts;
			System.arraycopy(data, 0, rawData, 0, size);
			this.leftSize = size;
			mutex.notify();
		}
	}

	public boolean isIdle()
	{
		return leftSize == 0 ? true : false;
	}

	public void setIdle()
	{
		leftSize = 0;
	}

	public void setRecording(boolean isRecording)
	{
		synchronized (mutex)
		{
			this.isRecording = isRecording;
			if (this.isRecording)
			{
				mutex.notify();
			}
		}
	}

	public boolean isRecording()
	{
		synchronized (mutex)
		{
			return isRecording;
		}
	}
}
